import { DataSource } from 'typeorm';
import { ProjectMember } from '../../../entities/project-member.entity';
import { Project } from '../../../entities/project.entity';
import { User } from '../../../entities/user.entity';
import { ProjectMemberRole, UserStatus } from '../../../types/enums';

/**
 * 项目成员种子数据
 * 负责初始化项目成员关系
 */
export class ProjectMemberSeed {
  constructor(private dataSource: DataSource) {}

  /**
   * 运行项目成员种子
   */
  async run(): Promise<void> {
    console.log('开始初始化项目成员数据...');

    const projectMemberRepository = this.dataSource.getRepository(ProjectMember);
    const projectRepository = this.dataSource.getRepository(Project);
    const userRepository = this.dataSource.getRepository(User);

    // 查找所有用户
    const adminUser = await userRepository.findOneBy({ username: 'admin' });
    const normalUser = await userRepository.findOneBy({ username: 'user' });
    const guestUser = await userRepository.findOneBy({ username: 'guest' });

    if (!adminUser || !normalUser || !guestUser) {
      console.log('未找到基础用户，跳过项目成员初始化');
      return;
    }

    // 查找所有项目
    const projects = await projectRepository.find();

    if (projects.length === 0) {
      console.log('未找到项目，跳过项目成员初始化');
      return;
    }

    // 设置当前日期作为加入时间
    const now = new Date();

    // 为每个项目添加成员
    for (const project of projects) {
      // 将管理员加入为领导者，由于没有确定ProjectMemberRole的确切值，使用通用角色
      const adminMember = projectMemberRepository.create({
        projectId: project.id,
        userId: adminUser.id,
        role: ProjectMemberRole.LEADER, // 假设有LEADER角色
        joinedAt: now,
        status: UserStatus.ACTIVE
      });
      await projectMemberRepository.save(adminMember);
      console.log(`添加用户 ${adminUser.username} 为项目 ${project.name} 的领导者`);

      // 将普通用户加入为成员
      const userMember = projectMemberRepository.create({
        projectId: project.id,
        userId: normalUser.id,
        role: ProjectMemberRole.MEMBER, // MEMBER角色确定存在
        joinedAt: now,
        status: UserStatus.ACTIVE
      });
      await projectMemberRepository.save(userMember);
      console.log(`添加用户 ${normalUser.username} 为项目 ${project.name} 的成员`);

      // 将访客用户加入为观察者
      const guestMember = projectMemberRepository.create({
        projectId: project.id,
        userId: guestUser.id,
        role: ProjectMemberRole.MEMBER, // 使用MEMBER角色，因为可能没有观察者角色
        joinedAt: now,
        status: UserStatus.ACTIVE
      });
      await projectMemberRepository.save(guestMember);
      console.log(`添加用户 ${guestUser.username} 为项目 ${project.name} 的成员`);
    }

    console.log('项目成员数据初始化完成');
  }
} 